# from django.http import JsonResponse
from backend.cews.models import TaskGroup, StockItemGroup
from backend.users.models import GroupSetting
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.mixins import (CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin, DestroyModelMixin)
from rest_framework.viewsets import GenericViewSet
from rest_framework import status as ResponseStatus

from backend.users.services import GroupSettingsService

from utils.decorators import request_data, error_response, check_group_permission

from .serializers import GroupSettingSerializer, PermissionSerializer, GroupSerializer, TaskGroupSerializer, StockItemGroupSerializer

from django.contrib.auth.models import Group, Permission
from django.contrib.auth import get_user_model

User = get_user_model()

class GroupSettingsViewSet(
    GenericViewSet,
    RetrieveModelMixin,
    ListModelMixin,
    UpdateModelMixin,
    CreateModelMixin,
    DestroyModelMixin
):
    serializer_class = GroupSettingSerializer
    queryset = GroupSetting.objects.all()

    @action(detail=False, methods=["post"], url_name="bulk_update_group_settings")
    @request_data(keys=['data'])
    @error_response()
    def bulk_update_group_settings(self,request,data):

        ok = GroupSettingsService.bulk_update_or_create(data)

        if ok:
            return Response(status=200,
                        data={
                            'code': 1,
                        }) 
        
        else:
            return Response(status=200,
                        data={
                            'code': 0,
                        }) 

    @action(detail=False, methods=["post"], url_name="get_setting_options")
    @request_data(keys=['groupname'])
    @error_response()
    def get_setting_options(self,request, groupname):
        ret = {}
        
        ret['username'] = [user.username for user in User.objects.filter(is_superuser=False) if not user.groups.filter(name=groupname).exists()]

        # print(ret)
        # ret['username'].append('ALL')
        # ret['group'].append('ALL')
        return Response(data=ret, status=200)

    @action(detail=False, methods=["post"], url_name="groupname")
    @request_data(keys=['groupname'])
    @error_response()
    def filter(self,request,groupname):

        queryset = GroupSettingsService.filter(groupname)
        print(queryset==None)
        data = GroupSettingSerializer(queryset, many=True).data
        
        if not data:
            max_id = 0
        else:
            max_id = GroupSetting.objects.latest('id').id
            

        return Response(status=200,
                    data={
                        'code': 1,
                        'data':data,
                        'max_id': max_id
                    }) 

    @action(detail=False, methods=["get"], url_name="list_permission")
    @error_response()
    def list_permission(self,request):

        queryset = Permission.objects.filter(codename__in=['can_do_maintenance_task','can_do_maintenance_by_stock_code'])
        data = PermissionSerializer(queryset, many=True).data
        
        return Response(status=200,
                    data={
                        'code': 1,
                        'data':data,
                    }) 
    
    @action(detail=False, methods=["get"], url_name="list_group")
    @error_response()
    def list_group(self,request):

        queryset = Group.objects.all().exclude(name__in=['S11&S21','S30','S40','G40'])
        data = GroupSerializer(queryset, many=True).data

        
        return Response(status=200,
                    data={
                        'code': 1,
                        'data':data,
                    }) 
    
    @action(detail=False, methods=["post"], url_name="create_group_and_permission_and_task")
    @request_data(keys=['group','can_do_task','can_do_sc','tasks', 'stockCodes'])
    @error_response()
    def create_group_and_permission_and_task(self,request,group,can_do_task,can_do_sc,tasks, stockCodes):

        data = GroupSettingsService.create_group_and_permission_and_task(group,can_do_task,can_do_sc,tasks, stockCodes)

        return Response(status=200,
                    data={
                        'code': 1,
                        'data':data,
                    }) 
    
    @action(detail=False, methods=["patch"], url_name="patch_group_and_permission")
    @request_data(keys=['group_id','can_do_task','can_do_sc', 'groupname', 'tasks', 'stockCodes'])
    @error_response()
    def patch_group_and_permission(self,request,group_id,can_do_task,can_do_sc, groupname, tasks, stockCodes):

        data = GroupSettingsService.patch_group_and_permission_and_task(group_id,can_do_task,can_do_sc, groupname, tasks, stockCodes)

        return Response(status=200,
                    data={
                        'code': 1,
                        'data':data,
                    }) 
    

    
    @action(detail=False, methods=["delete"], url_name="delete_group_setting")
    @request_data(keys=['id','username'])
    @error_response()
    def delete_group_setting(self,request,id, username):

        user = User.objects.filter(username=username).first()
        group_setting = GroupSetting.objects.get(pk=id)
        group = Group.objects.get(pk=group_setting.group.id)
        user.groups.remove(group)

        group_setting.delete()

        return Response(status=200,
                    data={
                        'code': 1,
                    }) 

    @action(detail=False, methods=["delete"], url_name="delete_group")
    @request_data(keys=['id'])
    @error_response()
    def delete_group(self,request,id):

        g = Group.objects.get(pk=id)
        g.delete()

        return Response(status=200,
                    data={
                        'code': 1,
                    }) 
    
    
    @action(detail=False, methods=["post"], url_name="get_group")
    @request_data(keys=['id'])
    @error_response()
    def get_group(self,request,id):

        queryset = Group.objects.filter(pk=id)
        group = GroupSerializer(queryset, many=True).data
        # print(group[0]['permissions'])
        return Response(status=200,
                    data={
                        'code': 1,
                        'data': group,
                    }) 
    
    @action(detail=False, methods=["delete"], url_name="delete_group_permission")
    @request_data(keys=['id', 'group_id'])
    @error_response()
    def delete_group_permission(self,request,id, group_id):

        g = Group.objects.get(pk=group_id)
        g.permissions.remove(id)

        return Response(status=200,
                    data={
                        'code': 1,
                    }) 
    
    @action(detail=False, methods=["delete"], url_name="delete_task_group")
    @request_data(keys=['id'])
    @error_response()
    def delete_task_group(self,request,id):

        tg = TaskGroup.objects.get(pk=id)
        tg.delete()

        return Response(status=200,
                    data={
                        'code': 1,
                    }) 
    
    @action(detail=False, methods=["post"], url_name="get_task_group")
    @request_data(keys=['id'])
    @error_response()
    def get_task_group(self,request,id):

        group = Group.objects.get(pk=id)

        queryset = TaskGroup.objects.filter(group=group)
        print(queryset)
        taskGroup = TaskGroupSerializer(queryset, many=True).data

        # print(taskGroup)
        return Response(status=200,
                    data={
                        'code': 1,
                        'data': taskGroup,
                    }) 
    
    @action(detail=False, methods=["post"], url_name="get_stock_item_group")
    @request_data(keys=['id'])
    @error_response()
    def get_stock_item_group(self,request,id):

        group = Group.objects.get(pk=id)

        queryset = StockItemGroup.objects.filter(group=group)
        print(queryset)
        stockItemGroup = StockItemGroupSerializer(queryset, many=True).data

        # print(taskGroup)
        return Response(status=200,
                    data={
                        'code': 1,
                        'data': stockItemGroup,
                    }) 
    
        
    @action(detail=False, methods=["delete"], url_name="delete_stock_group")
    @request_data(keys=['id'])
    @error_response()
    def delete_stock_group(self,request,id):

        tg = StockItemGroup.objects.get(pk=id)
        tg.delete()

        return Response(status=200,
                    data={
                        'code': 1,
                    }) 